package com.colorlight.cloud.gateway.core.connect;

import com.colorlight.cloud.auth.util.ConnectUtil;
import com.colorlight.cloud.common.constants.CommonConstants;
import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.mqtt.base.api.setting.ConnectSetting;
import com.colorlight.cloud.mqtt.base.core.properties.MqttProperties;
import com.colorlight.cloud.mqtt.base.entity.*;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;


/**
 * 这一层与实际的实现相关: 是连接层的具体实现，是协议的抽象层 没有具体的业务 ，将连接与下发抽象化
 * 流程上的一层 包含连接具体实现、方法上报的具体实现
 *
 * @author Demon
 * @date 8/1/2024  下午2:41
 */

@Configuration
public class ConnectSettingImpl implements ConnectSetting {
	
	
	private final MqttProperties mqttProperties;
	
	public ConnectSettingImpl(MqttProperties mqttProperties) {
		this.mqttProperties = mqttProperties;
	}
	
	@Override
	public ConnectDetail getConnectDetail() {
		String clientId = ConnectUtil.getClientId(mqttProperties.getDeviceName(), CommonConstants.CURRENT_TIME);
		String username = ConnectUtil.getDeviceName(mqttProperties.getEnvPrefix(), mqttProperties.getProductKey(), mqttProperties.getDeviceName());
		String password = ConnectUtil.getHmacSign(ConnectUtil.getPassword(mqttProperties.getDeviceName(), mqttProperties.getProductKey(), CommonConstants.CURRENT_TIME, mqttProperties.getEnvPrefix()), mqttProperties.getDeviceSecret());
		String[] topics = mqttProperties.getTopics();
		Integer[] qos = mqttProperties.getQos();
		if(topics.length!=qos.length){
			throw new ParameterException("配置主题与QOS数量不对应");
		}
		HashSet<TopicDetail> topicDetails = new HashSet<>(topics.length);
		for (int i = 0; i < topics.length; i++) {
			TopicDetail build = TopicDetail.builder()
					.qosEnum(QosEnum.getQos(qos[i]))
					.topic(topics[i])
					.build();
			topicDetails.add(build);
		}
		return ConnectDetail.builder()
				.brokerUrl(mqttProperties.getUrl())
				.clientId(clientId)
				.topicDetails(topicDetails)
				.username(username)
				.password(password)
				.build();
	}
}
